package netty.nio.zerocopy;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @Author: zhangrongqing
 * @Date: 2020/1/13 10:59
 */
public class NewIoClient {
    private static long FILE_SIZE = 8*1024*1024;

    public static void main(String[] args) throws  Exception{
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress(9090));
        String fileName = "C:\\Users\\zhang.rongqing\\Desktop\\学习计划\\JUC\\ReentranLock.xmind";

        //文件Channel
        FileChannel channel = new FileInputStream(fileName).getChannel();

        //发送
        long startTime = System.currentTimeMillis();

        //Linux中transforTo传输就可以
        //win中transforTo一次只能8M，如果需要的话需要分段传输
        Long transforCount = channel.transferTo(0,channel.size(),socketChannel);

        System.out.println("transforcount:" + transforCount);
        System.out.println("总时间:" + (System.currentTimeMillis() - startTime));

        channel.close();
        socketChannel.close();
    }

    public long calcFileSegmentCount(FileChannel fileChannel){
        long count = 0;
        try {
            count = fileChannel.size()/FILE_SIZE;
            if(count * FILE_SIZE != fileChannel.size()){
                return count++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return count;
    }
}
